<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2021/02/17
 * Time: 16:15
 * @link http://www.lmterp.cn
 */

namespace app\admin\controller\wms;

use app\admin\controller\BaseController;
use app\common\model\ChannelOrders;
use app\common\model\Orders;
use app\common\model\PurchaseExchange;
use app\common\model\PurchaseReturn;
use app\common\model\Warehouse;
use app\common\model\WarehouseAllot;
use app\common\model\WarehouseBorrow;
use app\common\model\WarehouseStock;
use app\common\service\product\StockService;

/**
 * 扫描出库
 * Class WscanController
 * @package app\admin\controller\wms
 */
class WscanController extends BaseController
{
    /**
     * 订单出库
     * @date 2021/02/20
     * @author longli
     */
    public function order()
    {
        if($this->request->isPost())
        {
            $sn = $this->request->post('sn', '', 'trim');
            if(empty($sn)) $this->error('非法请求', '', ["type" => "abnormal-operation"]);
            if(!($order = Orders::getByTsn($sn))) $this->error('订单不存在', '', ["type" => "order-not-exist"]);
            $html = view('info', [
                'sn' => $sn,
                'list' => $order->detail
            ])->getContent();
            $data = compact('html');
            // 计算重量
            $weight = $order->getWeight();
            if( $order->weight > 0 && abs( $order->weight - $weight) > intval(config('param.weight_offset')))
                $this->error('重量异常', '', $data + ["type" => "weight-exception"]);
            if(($msg = StockService::orderStock($order)) !== true)
                $this->error($msg, '', $data + ["type" => "wms-out-fail"]);
            $this->success("出库成功", '', $data + ["type" => "wms-out-success"]);
        }
        else
        {
            return $this->fetch('order');
        }
    }

    /**
     * 订单扫描称重
     * @date 2021/02/22
     * @author longli
     */
    public function weight()
    {
        if($this->request->isPost())
        {
            $sn = $this->request->post('sn', '', 'trim');
            $weight = $this->request->post('weight', 0, 'intval');
            if(empty($sn) || empty($weight)) $this->error('非法请求', '', ["type" => "abnormal-operation"]);
            if(!($order = Orders::getByTsn($sn))) $this->error('订单不存在', '', ["type" => "order-not-exist"]);
            $html = view('info', [
                'sn' => $sn,
                'list' => $order->detail
            ])->getContent();
            $data = compact('html');
            $offset = intval(config('param.weight_offset'));
            $sw = $order->getWeight();
            if(abs($weight - $sw) > $offset)
                $this->error('重量异常', '', $data + ["type" => "weight-exception"]);
            // 更新订单状态
            if($order->getData('order_status') < Orders::ORDER_WAIT_OUT)
                $order->order_status = Orders::ORDER_WAIT_OUT;
            $order->weight = $weight;
            $order->save();
            if($chOrder = ChannelOrders::get(['order_id' => $order->order_id]))
            {
                $chOrder->weight = $weight;
                $chOrder->save();
            }
            $this->success("操作成功", '', $data + ["type" => "operation-success"]);
        }
        else
        {
            return $this->fetch('weight');
        }
    }

    /**
     * 调拨出库
     * @date 2021/02/20
     * @author longli
     */
    public function allot()
    {
        if($this->request->isPost())
        {
            $sn = $this->request->post('sn', '', 'trim');
            if(empty($sn)) $this->error('非法请求', '', ["type" => "abnormal-operation"]);
            $allot = WarehouseAllot::get(['track_num' => $sn]);
            if(!$allot && !($allot = WarehouseAllot::getBySn($sn)))
                $this->error('调拨单不存在', '', ["type" => "order-not-exist"]);
            $html = view('info', [
                'sn' => $allot->allot_sn,
                'list' => $allot->info
            ])->getContent();
            $data = compact('html');
            if(($msg = StockService::allotOut($allot->allot_sn)) !== true)
                $this->error($msg, '', $data + ["type" => "wms-out-fail"]);
            $this->success("出库成功", '', $data + ["type" => "wms-out-success"]);
        }
        else
        {
            $this->assign('warehouse', Warehouse::getAll());
            return $this->fetch('allot');
        }
    }

    /**
     * 借用出库
     * @date 2021/02/20
     * @author longli
     */
    public function borrow()
    {
        if($this->request->isPost())
        {
            $sn = $this->request->post('sn', '', 'trim');
            if(empty($sn)) $this->error('非法请求', '', ["type" => "abnormal-operation"]);
            if(!($borrow = WarehouseBorrow::getBySn($sn)))
                $this->error('借用单不存在', '', ["type" => "order-not-exist"]);
            $html = view('info', [
                'sn' => $sn,
                'list' => $borrow->info
            ])->getContent();
            $data = compact('html');
            if(($msg = StockService::borrowOut($sn)) !== true)
                $this->error($msg, '', $data + ["type" => "wms-out-fail"]);
            $this->success("出库成功", '', $data + ["type" => "wms-out-success"]);
        }
        else
        {
            return $this->fetch('borrow');
        }
    }

    /**
     * 采购退货出库
     * @date 2021/03/19
     * @author longli
     */
    public function purchase_ren()
    {
        if($this->request->isPost())
        {
            $sn = $this->request->post('sn', '', 'trim');
            if(empty($sn)) $this->error('非法请求', '', ["type" => "abnormal-operation"]);
            $ren = PurchaseReturn::get(['track_num' => $sn]);
            if(!$ren && !($ren = PurchaseReturn::getBySn($sn))) $this->error('退货单不存在', '', ["type" => "order-not-exist"]);
            $html = view('info', [
                'sn' => $ren->return_sn,
                'list' => $ren->info
            ])->getContent();
            $data = compact('html');
            if(($msg = StockService::purchaseReturnOut($ren)) !== true)
                $this->error($msg, '', $data + ["type" => "wms-out-fail"]);
            $this->success("出库成功", '', $data + ["type" => "wms-out-success"]);
        }
        else
        {
            $this->assign('placeholder', '采购退货单号/追踪号');
            return $this->fetch('purchase');
        }
    }

    /**
     * 采购换货出库
     * @date 2021/03/23
     * @author longli
     */
    public function purchase_ex()
    {
        if($this->request->isPost())
        {
            $sn = $this->request->post('sn', '', 'trim');
            if(empty($sn)) $this->error('非法请求', '', ["type" => "abnormal-operation"]);
            $exchange = PurchaseExchange::get(['track_num' => $sn]);
            if(!$exchange && !($exchange = PurchaseExchange::getBySn($sn))) $this->error('换货单不存在', '', ["type" => "order-not-exist"]);
            $html = view('info', [
                'sn' => $exchange->exchange_sn,
                'list' => $exchange->info
            ])->getContent();
            $data = compact('html');
            if(($msg = StockService::purchaseExchangeOut($exchange)) !== true)
                $this->error($msg, '', $data + ["type" => "wms-out-fail"]);
            $this->success("出库成功", '', $data + ["type" => "wms-out-success"]);
        }
        else
        {
            $this->assign('placeholder', '采购换货单号/追踪号');
            return $this->fetch('purchase');
        }
    }

    /**
     * 报损出库
     * @date 2021/02/20
     * @author longli
     */
    public function damage()
    {
        if($this->request->isAjax())
        {
            if($this->request->isPost())
            {
                // 执行报损出库
                $validate = \think\facade\Validate::make([
                    'sku'  => 'require|array',
                    'qty'  => 'require|array',
                ],[
                    'sku.require' => 'SKU必填',
                    'sku.array' => 'SKU必须是数组',
                    'qty.require' => '数量必填',
                    'qty.array' => '数量必须是数组',
                ]);
                $data = $this->request->post();
                if(!$validate->batch()->check($data)) $this->error(join(', ', $validate->getError()));
                foreach($data['sku'] as $k => $sku)
                {
                    if($data['qty'][$k] < 1)
                        $this->error("SKU【{$sku}】数量不能小于1", '', ["type" => "abnormal-operation"]);
                }
                $warehouse = Warehouse::get($this->warehouse->warehouse_id);
                \think\Db::startTrans();
                foreach($data['sku'] as $k => $sku)
                {
                    $stock = WarehouseStock::getWarehouseBySku($warehouse, $sku);
                    if(($msg = StockService::damageOut($stock, $data['qty'][$k])) !== true)
                    {
                        \think\Db::rollback();
                        $this->error($msg, '', ["type" => "wms-out-fail"]);
                    }
                }
                \think\Db::commit();
                $this->success("出库成功", '', ["type" => "wms-out-success"]);
            }
            else
            {
                $sku = $this->request->get('sku', '', 'trim');
                if(empty($sku)) $this->error('非法请求', '', ["type" => "abnormal-operation" ]);
                $wid = $this->warehouse->warehouse_id;
                if(!WarehouseStock::hasSku($wid, $sku))
                    $this->error('商品不存在', '', ["type" => "product-not-exist"]);
                // 渲染报损详情模板
                $stock = WarehouseStock::getWarehouseBySku($wid, $sku);
                $html = view('damage_info', [
                    'stock' => $stock
                ])->getContent();
                $data = compact('html');
                $this->success('加载成功', '', $data + ['sku' => $stock->sku]);
            }

        }
        else
        {
            // 渲染报损模板
            return $this->fetch('damage');
        }
    }
}